/**
 * @constructor aliyun form
 */

import React from 'react';
import PropTypes from 'prop-types';
import { Field, Input, Balloon, Checkbox, Form } from '@teamix/ui';
import { YunxiaoIcon } from '@alife/devops-ui';
import exceed from 'utils/apimap';
import BuildRuleModal from './rulesModal';
import docs from 'utils/docs';
import intl from '../../../locale';

const { pathResource } = window.FORCE;
const FormItem = Form.Item;
const formItemLayout = {
  labelCol: {
    span: 6,
  },

  wrapperCol: {
    span: 14,
  },
};

const whitelistHolder = intl.get({
  id: 'code-assets.projectSecuritySettingModal.sensitive.EnterTheFilePathSeparate',
  defaultMessage: '请输入文件路径，多行以换行隔开',
});
const triggerInfo = [
  {
    label: intl.get({
      id: 'code-assets.projectSecuritySettingModal.sensitive.CodeSubmissionTriggersScanning',
      defaultMessage: '代码提交触发扫描',
    }),
    value: 'commit_trigger',
  },

  {
    label: intl.get({
      id: 'code-assets.projectSecuritySettingModal.sensitive.MergeRequestsToTriggerScanning',
      defaultMessage: '合并请求触发扫描',
    }),
    value: 'mr_trigger',
  },
];

export default class ImportProjectByUrlModal extends React.Component {
  static propTypes = {
    data: PropTypes.object,
    modalPlugin: PropTypes.object,
  };

  static defaultProps = {
    data: {},
    modalPlugin: {},
  };

  constructor(props) {
    super(props);
    this.field = new Field(this);
    this.inited = true;
    this.state = {
      rulesVisible: false,
      whitelistCount: 0,
    };
  }

  componentDidMount() {
    this.fetchEnabledRulesCount();
    this.initData();
  }

  initData = () => {
    const { data, modalPlugin } = this.props;

    const key = modalPlugin && modalPlugin.key;
    if (!key) {
      return;
    }
    const detail = data && data[key];
    const { commit_trigger, mr_trigger, whitelist = '', enabled } = detail;
    const trigger = [];
    // 已开启读取服务设置，未开启默认勾选
    if (enabled) {
      if (commit_trigger) {
        trigger.push('commit_trigger');
      }
      if (mr_trigger) {
        trigger.push('mr_trigger');
      }
    } else {
      trigger.push('commit_trigger');
      trigger.push('mr_trigger');
    }
    this.field.setValues({
      trigger,
      whitelist,
    });
  };

  getReqData = () => {
    const { modalPlugin } = this.props;
    const params = {
      commit_trigger: false,
      enabled: true,
      mr_trigger: false,
      whitelist: '',
    };

    const formData = this.field.getValues();
    if (formData.trigger) {
      params.commit_trigger = formData.trigger.includes('commit_trigger');
      params.mr_trigger = formData.trigger.includes('mr_trigger');
    }
    params.whitelist = this.removeEmptyLine(formData.whitelist) || '';
    return {
      key: modalPlugin.key,
      params,
    };
  };

  fetchEnabledRulesCount = () => {
    const { modalPlugin: item } = this.props;
    exceed
      .fetch({
        api: 'projects.builds.rules.count',
        params: {
          projectId: pathResource.id,
        },

        data: {
          plugin: item.plugin,
        },
      })
      .then((result) => {
        this.setState({
          whitelistCount: result,
        });
      })
      .fail((err) => {
        console.log(err);
      });
  };

  removeEmptyLine = (value) => {
    if (value) {
      const lines = value.trim().split('\n');
      return lines
        .map((line) => line.trim())
        .filter((line) => line !== '')
        .join('\n');
    }
    return value;
  };

  checkWhitelistValid = () => {
    const whitelist = this.field.getValue('whitelist');
    if (!whitelist) {
      return true;
    }
    const lines = this.field.getValue('whitelist').split('\n');
    for (let i = 0; i < lines.length; i++) {
      if (
        lines[i].trim() === '**' ||
        lines[i].trim() === '/**' ||
        lines[i].trim() === '/**/*' ||
        lines[i].trim() === '/*/**' ||
        lines[i].trim() === '**/*' ||
        lines[i].trim() === '*/**' ||
        lines[i].trim() === '**/**' ||
        lines[i].trim() === '/**/**'
      ) {
        return false;
      }
    }
    return true;
  };

  render() {
    const { whitelistCount } = this.state;
    const { modalPlugin: item } = this.props;
    const { init } = this.field;

    return (
      <div className="sensitive">
        <Form {...formItemLayout} field={this.field} labelAlign="top">
          <FormItem
            label={
              <div>
                {intl.get({
                  id: 'code-assets.projectSecuritySettingModal.sensitive.TriggerMode',
                  defaultMessage: '• 触发方式',
                })}
              </div>
            }
          >
            <Checkbox.Group itemDirection="hoz" {...init('trigger')}>
              {/* 过滤没有提供的项 */}
              {triggerInfo.map((it) => {
                return (
                  <Checkbox value={it.value} key={it.value}>
                    {it.label}
                  </Checkbox>
                );
              })}
            </Checkbox.Group>
          </FormItem>
          <FormItem
            label={
              <div>
                {intl.get({
                  id: 'code-assets.projectSecuritySettingModal.sensitive.DetectionRules',
                  defaultMessage: '• 检测规则',
                })}
              </div>
            }
            className="sensitive-rule"
          >
            <div className="sensitive-rule-subtitle">
              {intl.get({
                id: 'code-assets.projectSecuritySettingModal.sensitive.CurrentlyEnabled',
                defaultMessage: '当前启用',
              })}
              {whitelistCount}
              {intl.get({
                id: 'code-assets.projectSecuritySettingModal.sensitive.Rule',
                defaultMessage: '条规则',
              })}
              <a type="primary" onClick={() => this.setState({ rulesVisible: true })}>
                {intl.get({
                  id: 'code-assets.projectSecuritySettingModal.sensitive.See',
                  defaultMessage: '查看',
                })}
              </a>
            </div>
            <BuildRuleModal
              isModalOpen={this.state.rulesVisible}
              taskName={item.title}
              taskKey={item.plugin}
              closeFn={() => {
                this.setState({
                  rulesVisible: false,
                });
              }}
            />
          </FormItem>
          <FormItem
            label={
              <div>
                {intl.get({
                  id: 'code-assets.projectSecuritySettingModal.sensitive.FileWhitelist',
                  defaultMessage: '• 文件白名单',
                })}

                <Balloon
                  align="t"
                  trigger={<YunxiaoIcon type="question-line" className="setting-card-help-icon" />}
                  closable={false}
                >
                  <a
                    type="primary"
                    target="_blank"
                    href={docs('fileWhitelistRules')}
                    rel="noreferrer"
                  >
                    {intl.get({
                      id: 'code-assets.projectSecuritySettingModal.sensitive.HowDoIUseA',
                      defaultMessage: '如何使用文件白名单？',
                    })}
                  </a>
                </Balloon>
              </div>
            }
            className="sensitive-whitelist"
          >
            <div className="sensitive-whitelist-subtitle">
              {intl.get({
                id: 'code-assets.projectSecuritySettingModal.sensitive.YouCanAddFilesThat',
                defaultMessage: '支持将无需扫描的文件加入白名单',
              })}
            </div>
            <Input.TextArea
              hasLimitHint
              maxLength={3000}
              className="sensitive-whitelist-text"
              placeholder={whitelistHolder}
              {...init('whitelist')}
            />

            {!this.checkWhitelistValid() && (
              <div className="next-form-item-help whitelist-warning-help">
                <YunxiaoIcon type="warning-fill" />
                <span className="next-form-item-help-text">
                  {intl.get({
                    id: 'code-assets.projectSecuritySettingModal.sensitive.TheCurrentSettingsDoNot',
                    defaultMessage: '当前设置不扫描任何文件，存在敏感信息泄露风险',
                  })}
                </span>
              </div>
            )}

            <div className="sensitive-whitelist-tips-card">
              <div className="sensitive-whitelist-tips">
                ？
                <span style={{ paddingLeft: '5px' }}>
                  {intl.get({
                    id: 'code-assets.projectSecuritySettingModal.sensitive.MatchesAnyOneCharacterSuch',
                    defaultMessage:
                      '匹配任意1个字符，如：codeup/t?st.java 跳过 codeup/test.java 或 codeup/tast.java',
                  })}
                </span>
              </div>
              <div className="sensitive-whitelist-tips">
                *
                <span style={{ paddingLeft: '11px' }}>
                  {intl.get({
                    id: 'code-assets.projectSecuritySettingModal.sensitive.MatchesOrMoreCharactersFor',
                    defaultMessage:
                      '匹配0或多个字符，如：codeup/*.java 跳过 codeup 目录下所有 Java 文件',
                  })}
                </span>
              </div>
              <div className="sensitive-whitelist-tips">
                **
                <span style={{ paddingLeft: '6px' }}>
                  {intl.get({
                    id: 'code-assets.projectSecuritySettingModal.sensitive.MatchesOrMoreDirectoriesFor',
                    defaultMessage: '匹配0或多个目录，如：**.java 跳过所有目录下的 Java 文件',
                  })}
                </span>
              </div>
            </div>
          </FormItem>
        </Form>
      </div>
    );
  }
}
